package com.ycsj.goldmedalnewconcept.teacher.activity;

import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.SpKeys;
import com.ycsj.common.doubleclick.AntiShake;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.common.utils.ScreenUtils;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.common.view.scroll.MyGridView;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.adapter.UnitGvAdapter;
import com.ycsj.goldmedalnewconcept.common.bean.UnitGvInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpCallBack;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.LayoutUtils;
import com.ycsj.goldmedalnewconcept.teacher.adapter.ClassGvAdapter;
import com.ycsj.goldmedalnewconcept.teacher.bean.ClassInfo;
import com.ycsj.goldmedalnewconcept.teacher.bean.CourseData;
import com.ycsj.goldmedalnewconcept.teacher.utils.ClassPoputil;
import com.ycsj.goldmedalnewconcept.teacher.utils.ClassUtil;
import com.ycsj.goldmedalnewconcept.view.MyScrollView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 金牌新概念-课程进度-选择单元界面
 * Created by Administrator on 2019/5/6
 */
public class TeacherCourseProgressActivity extends BaseActivity {

    @BindView(R.id.lv_edit)
    ImageView lv_edit;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.scrollview)
    MyScrollView scrollView;
    @BindView(R.id.rl_contain)
    RelativeLayout rlContain;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.mgv)
    MyGridView mgv;

    //所有班级的列表
    private List<ClassInfo.ListBean> classInfos;

    //展示班级列表的适配器
    private ClassGvAdapter classGvAdapter;

    //记录弹出展示班级列表PopUpWindow的选中位置的值,默认第一个被选中
    private int popSelectedPos = 0;

    //展示单元栏目的数据格式
    private List<UnitGvInfo> unitDatas;

    //背景图的设计宽高
    private int width = 750;
    private int height = 10672;

    //展示单元选项的GridView适配器
    private UnitGvAdapter gvAdapter;

    //用于存放所有布局参数
    private List<Integer> paramsMarginlefts;
    private List<Integer> paramsMargintops;
    private int screenWidth;
    //用于放置所有按钮的线性布局的高度
    private int llheight;

    //每个Unit单元的TextView的大小
    private int itemWidth = 52;
    private int itemHeight = 46;

    //添加Unit单元的布局参数
    private RelativeLayout.LayoutParams lp;

    //跳转的标识,用于区分是哪个界面点击跳转来
    private int type;

    //是否获取班级列表数据完成的标识,没完成之前点击选择班级的弹框提示正在加载,不允许点击
    private boolean isLoadClassCompleted = false;


    private int isLoadClassnum = 0;

    private List<Integer> lesson_list;

    @Override
    protected int getContentLayout() {
        return R.layout.teacher_activity_choose_unit;
    }

    @Override
    protected void init() {
        //沉浸式
        initStateBar();

        //初始化标题
        initTitle();

        //初始化单元导航栏
        initGv();

        //获取班级
        httpClass();

    }


    /**
     * 初始化标题栏
     */
    private void initTitle() {

        tvTitle.setText("课程进度");

        lv_edit.setVisibility(View.VISIBLE);

        lv_edit.setImageDrawable(getResources().getDrawable(R.drawable.common_class));

    }


    /**
     * 动态设置背景图的宽高
     */
    private void initParamsBg() {
        screenWidth = ScreenUtils.getScreenWidth(this);
        //计算高度,根据设计图的宽高比来动态配置
        llheight = screenWidth * height / width;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(screenWidth, llheight);
        rlContain.setLayoutParams(lp);
    }

    /**
     * 动态计算72个单元的布局宽和高
     */
    private void initPositon() {

        paramsMarginlefts = LayoutUtils.getMarinLefts(screenWidth);

        paramsMargintops = LayoutUtils.getMarinTops(llheight);

        //动态添加按钮布局
        if (paramsMarginlefts.size() != 0 && paramsMargintops.size() != 0) {
            for (int i = 1; i <= paramsMargintops.size(); i++) {
                TextView tv = (TextView) View.inflate(this, R.layout.unit_item_tv, null);
                tv.setTag((73 - i));
                lp = new RelativeLayout.LayoutParams(UiUtils.dp2px(itemWidth), UiUtils.dp2px(itemHeight));
                lp.topMargin = paramsMargintops.get(i - 1);
                lp.leftMargin = paramsMarginlefts.get(i - 1);
                tv.setText((73 - i) + "");
                //配置TextView的paddingleft和paddingtop,确保文字居中
                if (i > 63 && i <= paramsMargintops.size()) {
                    //文字为1到9时
                    tv.setPadding(UiUtils.dp2px(18), UiUtils.dp2px(7), 0, 0);
                } else {
                    //文字为两位数数
                    tv.setPadding(UiUtils.dp2px(12), UiUtils.dp2px(7), 0, 0);
                }

                boolean include = false;
                for (int j = 0; j < lesson_list.size(); j++) {

                    //这里还需要根据服务器返回的状态来设置Unit的背景以及是否可以点击
                    if (lesson_list.get(j) == (73 - i)) {
                        include = true;
                    }
                }

                if (include) {
                    tv.setBackgroundResource(R.drawable.tv_unit_blue);
                } else {
                    tv.setBackgroundResource(R.drawable.tv_unit_open);
                }

                //背景状态值有:new_index(新),tv_unit_open,tv_unit_blue三种状态

                rlContain.addView(tv, lp);
            }
        }
    }


    /**
     * 初始化单元导航栏
     */
    private void initGv() {

        unitDatas = new ArrayList<>();
        UnitGvInfo oneUnitGvInfo = new UnitGvInfo(R.drawable.one_select, R.drawable.one_unselect, true);
        UnitGvInfo twoUnitGvInfo = new UnitGvInfo(R.drawable.two_select, R.drawable.two_unselect, false);
        UnitGvInfo threeUnitGvInfo = new UnitGvInfo(R.drawable.three_select, R.drawable.three_unselect, false);
        UnitGvInfo fourUnitGvInfo = new UnitGvInfo(R.drawable.four_select, R.drawable.four_unselect, false);

        unitDatas.add(oneUnitGvInfo);
        unitDatas.add(twoUnitGvInfo);
        unitDatas.add(threeUnitGvInfo);
        unitDatas.add(fourUnitGvInfo);

        gvAdapter = new UnitGvAdapter(this, unitDatas, R.layout.item_gv_unit);

        mgv.setAdapter(gvAdapter);

        //条目点击事件
        mgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                //根据点击的条目让ScrollView滚动到指定位置
                switch (position) {
                    case 0:
                        //滚动到底部
                        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                        break;
                    case 1://顶部停留在19单元
                        scrollView.post(new Runnable() {
                            @Override
                            public void run() {
                                TextView tv = (TextView) rlContain.getChildAt(53);
                                scrollView.smoothScrollTo(0, tv.getTop() - ScreenUtils.getScreenHeight(TeacherCourseProgressActivity.this) + UiUtils.dp2px(80));
                            }
                        });
                        break;
                    case 2://37
                        scrollView.post(new Runnable() {
                            @Override
                            public void run() {
                                TextView tv = (TextView) rlContain.getChildAt(35);
                                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) tv.getLayoutParams();
                                scrollView.smoothScrollTo(0, tv.getTop() - ScreenUtils.getScreenHeight(TeacherCourseProgressActivity.this) + UiUtils.dp2px(80));
                            }
                        });
                        break;
                    case 3:
                        //滚动到顶部
                        scrollView.fullScroll(ScrollView.FOCUS_UP);
                        break;
                }

                if (unitDatas.get(position).isSelected) {
                    return;
                } else {
                    sysGvState(position);
                }
            }
        });
    }

    /**
     * 请求班级里列表数据
     */
    private void httpClass() {
        ClassUtil.httpClass(null, this, new ClassUtil.onSuccessListener() {
            @Override
            public void onSuccess(List<ClassInfo.ListBean> datas) {
                //回调班级数据
                classInfos = datas;

                //证明有班级
                lv_edit.setVisibility(View.VISIBLE);

                //改变加载完成的标记
                isLoadClassCompleted = true;

                //请求页面列表数据
                http(popSelectedPos);

                //保存班级
                SPUtil.put(TeacherCourseProgressActivity.this, SpKeys.TEACHERCLASS, classInfos.get(popSelectedPos).getNum() + "");

            }

            @Override
            public void hasNoData() {
                //没有班级,不显示顶部的切换班级的按钮和
                lv_edit.setVisibility(View.INVISIBLE);
            }
        });
    }

    /**
     * ScrollView的滚动监听事件
     */
    private void initScrollListener() {

        //初次进入的时候让ScrollView滚动到底部
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });

        //滚动监听
        scrollView.setOnScrollListener(new MyScrollView.OnScrollListener() {
            @Override
            public void onScroll(int scrollY) {
                //判断滚动距离,同步顶部Unit单元的同步状态

                TextView tv53 = (TextView) rlContain.getChildAt(53); //对应19
                int top53Distance = tv53.getTop() - ScreenUtils.getScreenHeight(TeacherCourseProgressActivity.this) + UiUtils.dp2px(80);

                TextView tv35 = (TextView) rlContain.getChildAt(35);//对应3
                int top35Distance = tv35.getTop() - ScreenUtils.getScreenHeight(TeacherCourseProgressActivity.this) + UiUtils.dp2px(80);

                TextView tv17 = (TextView) rlContain.getChildAt(17);//对应3
                int top17Distance = tv17.getTop() - ScreenUtils.getScreenHeight(TeacherCourseProgressActivity.this) + UiUtils.dp2px(80);

                //从下往上滑
                if (scrollY > top53Distance) {
                    //1-1选中
                    sysGvState(0);
                } else if (scrollY > top35Distance) {
                    //1-2选中,滚动距离为9978-5615 对应的是53-35
                    sysGvState(1);
                } else if (scrollY > top17Distance) {
                    //1-3选中,滚动距离为5615-221 对应的是35-17
                    sysGvState(2);
                } else if (scrollY > 0) {
                    //1-4选中
                    sysGvState(3);
                }
            }
        });
    }

    /**
     * @param pos
     */
    private void sysGvState(int pos) {
        for (int i = 0; i < unitDatas.size(); i++) {
            if (i == pos) {
                unitDatas.get(i).isSelected = true;
            } else {
                unitDatas.get(i).isSelected = false;
            }
        }
        gvAdapter.notifyDataSetChanged();
    }

    /**
     * 选择班级的弹框
     */
    private void showClassPop() {
        ClassPoputil.showClassPop(this, classInfos, popSelectedPos, llTitle, new ClassPoputil.onPopItemClickListener() {
            @Override
            public void onItemClick(int pos) {
                //记录当前点击条目的位置
                popSelectedPos = pos;

                //请求页面数据
                http(popSelectedPos);
            }
        });
    }

    /**
     * 获取服务器数据
     */
    private void http(int pos) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "17");
        map.put("userID", AccountUtils.getAccount(this));
//        map.put("acc", AccountUtils.getAccount(this));
//        map.put("role", AccountUtils.getRole(this));
        map.put("classnum", classInfos.get(pos).getNum() + "");
//        map.put("apptoken", AccountUtils.getToken(this));
//        map.put("platform", "2");

        HttpUtils.post(HttpAddress.COURSEPROGRESS, map, this,
                new HttpCallBack<CourseData>() {

                    @Override
                    public void onSuccess(CourseData info) {
                        if (info != null) {
                            if ("1".equals(info.getState())) {

                                lesson_list = info.getUnit();

                                if (isLoadClassnum == 0) {

                                    //动态配置滚动布局的宽高
                                    initParamsBg();

                                    //动态计算每个按钮的布局参数宽和高
                                    initPositon();

                                    //设置ScrollView的滚动监听事件
                                    initScrollListener();

                                } else {
                                    for (int i = 0; i < rlContain.getChildCount(); i++) {

                                        boolean include = false;
                                        for (int j = 0; j < lesson_list.size(); j++) {

                                            //这里还需要根据服务器返回的状态来设置Unit的背景以及是否可以点击
                                            if (lesson_list.get(j) == (i + 1)) {
                                                include = true;
                                            }
                                        }

                                        if (include) {
                                            rlContain.getChildAt(71 - i).setBackgroundResource(R.drawable.tv_unit_blue);
                                        } else {
                                            rlContain.getChildAt(71 - i).setBackgroundResource(R.drawable.tv_unit_open);
                                        }
                                    }
                                }

                                //配置完成
                                isLoadClassnum++;
                            } else {
                                ToastUtils.showShort("服务器错误");
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {
                    }
                });
    }


    /**
     * 点击事件
     *
     * @param v
     */
    @OnClick({R.id.iv_back, R.id.lv_edit})
    public void clickEvent(View v) {
        if (AntiShake.check(v)) {
            ToastUtils.showShort("");
        } else {
            switch (v.getId()) {
                case R.id.iv_back:
                    //返回
                    finish();
                    break;
                case R.id.lv_edit:
                    //选择班级
                    if (isLoadClassCompleted) {
                        //弹出选择班级的PopUpWindow
                        showClassPop();
                    } else {
                        //没加载完成
                    }
                    break;
            }
        }
    }
}







